<template>
  <div class="message-center">
    <div class="page-header">
      <h2>消息中心</h2>
    </div>
    
    <el-card class="chat-container" v-loading="loading">
      <div class="chat-layout">
        <!-- 联系人列表 -->
        <div class="contacts-list">
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索联系人"
              prefix-icon="el-icon-search"
              clearable
            />
          </div>
          <div class="contacts-scroll">
            <div
              v-for="contact in filteredContacts"
              :key="contact.id"
              class="contact-item"
              :class="{ active: currentContact && currentContact.id === contact.id }"
              @click="selectContact(contact)"
            >
              <el-avatar :size="40" :src="contact.avatar || '/default-avatar.png'"></el-avatar>
              <div class="contact-info">
                <div class="contact-name">{{ contact.realName }}</div>
                <div class="contact-role">{{ contact.role === 'teacher' ? '教师' : '学生' }}</div>
              </div>
              <div v-if="contact.unreadCount" class="unread-badge">{{ contact.unreadCount }}</div>
            </div>
            <el-empty v-if="filteredContacts.length === 0" description="暂无联系人" />
          </div>
        </div>
        
        <!-- 聊天窗口 -->
        <div class="chat-window">
          <template v-if="currentContact">
            <div class="chat-header">
              <span>{{ currentContact.realName }}</span>
              <span class="contact-role">{{ currentContact.role === 'teacher' ? '教师' : '学生' }}</span>
            </div>
            
            <div class="chat-messages" ref="messageContainer">
              <div v-if="messages.length === 0" class="empty-messages">
                <el-empty description="暂无消息记录" />
              </div>
              <template v-else>
                <div
                  v-for="message in messages"
                  :key="message.id"
                  class="message-item"
                  :class="{ 'message-self': message.senderId === userStore.userId }"
                >
                  <el-avatar 
                    :size="36" 
                    :src="message.senderId === userStore.userId ? userStore.avatar : currentContact.avatar || '/default-avatar.png'"
                  ></el-avatar>
                  <div class="message-content">
                    <div class="message-text" v-if="message.type === 'text'">{{ message.content }}</div>
                    <div class="message-image" v-else-if="message.type === 'image'">
                      <el-image :src="message.content" :preview-src-list="[message.content]"></el-image>
                    </div>
                    <div class="message-time">{{ formatDate(message.sendTime) }}</div>
                  </div>
                </div>
              </template>
            </div>
            
            <div class="chat-input">
              <el-input
                v-model="messageText"
                type="textarea"
                :rows="3"
                placeholder="输入消息内容..."
                @keyup.enter.native.exact="sendTextMessage"
              />
              <div class="input-actions">
                <el-upload
                  :action="null"
                  :http-request="uploadImage"
                  :show-file-list="false"
                  accept="image/*"
                >
                  <el-button icon="el-icon-picture-outline" circle></el-button>
                </el-upload>
                <el-button type="primary" @click="sendTextMessage" :disabled="!messageText.trim()">发送</el-button>
              </div>
            </div>
          </template>
          
          <el-empty v-else description="请选择联系人开始聊天" />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useUserStore } from '@/store/user';
import { getChatHistory, sendMessage, markAllAsRead, getUnreadCount, getContacts, getUnreadMessages } from '@/api/chat';
import { uploadChatImage } from '@/api/file';
import { formatDate } from '@/utils/format';

const userStore = useUserStore();
const loading = ref(false);
const contacts = ref([]);
const messages = ref([]);
const currentContact = ref(null);
const messageText = ref('');
const searchKeyword = ref('');
const messageContainer = ref(null);
const socket = ref(null);

// 过滤后的联系人列表
const filteredContacts = computed(() => {
  if (!searchKeyword.value) return contacts.value;
  const keyword = searchKeyword.value.toLowerCase();
  return contacts.value.filter(contact => 
    contact.realName.toLowerCase().includes(keyword) || 
    contact.username.toLowerCase().includes(keyword)
  );
});

// 初始化WebSocket连接
const initWebSocket = () => {
  if (socket.value) {
    socket.value.close();
  }
  
  const wsUrl = `${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//${window.location.host}/api/ws/chat/${userStore.userId}`;
  socket.value = new WebSocket(wsUrl);
  
  socket.value.onopen = () => {
    console.log('WebSocket连接已建立');
  };
  
  socket.value.onmessage = (event) => {
    try {
      const message = JSON.parse(event.data);
      if (currentContact.value && message.senderId === currentContact.value.id) {
        messages.value.push(message);
        scrollToBottom();
      }
      // 更新未读消息数量
      loadUnreadCounts();
    } catch (error) {
      console.error('消息解析错误', error);
    }
  };
  
  socket.value.onerror = (error) => {
    console.error('WebSocket错误', error);
  };
  
  socket.value.onclose = () => {
    console.log('WebSocket连接已关闭');
  };
};

// 加载联系人列表
const loadContacts = async () => {
  try {
    loading.value = true;
    // 使用API获取联系人列表，传递用户ID
    const response = await getContacts(userStore.userId);
    if (response.code === 200) {
      contacts.value = response.data.map(contact => ({
        ...contact,
        unreadCount: 0 // 初始未读消息数量为0
      }));
      
      // 加载未读消息数量
      loadUnreadCounts();
    } else {
      ElMessage.error('获取联系人列表失败');
    }
  } catch (error) {
    console.error('获取联系人列表失败', error);
    ElMessage.error('获取联系人列表失败');
  } finally {
    loading.value = false;
  }
};

// 加载未读消息数量
const loadUnreadCounts = async () => {
  try {
    // 获取当前用户的所有未读消息
    const unreadResponse = await getUnreadMessages(userStore.userId);
    if (unreadResponse.code === 200) {
      // 按发送者分组统计未读消息
      const unreadMessages = unreadResponse.data || [];
      const unreadCountMap = {};
      
      // 统计每个联系人的未读消息数量
      unreadMessages.forEach(message => {
        if (!unreadCountMap[message.senderId]) {
          unreadCountMap[message.senderId] = 0;
        }
        unreadCountMap[message.senderId]++;
      });
      
      // 更新联系人列表中的未读消息数量
      contacts.value.forEach(contact => {
        contact.unreadCount = unreadCountMap[contact.id] || 0;
      });
    }
  } catch (error) {
    console.error('获取未读消息数量失败', error);
  }
};

// 选择联系人
const selectContact = async (contact) => {
  if (currentContact.value && currentContact.value.id === contact.id) {
    return;
  }
  
  currentContact.value = contact;
  messages.value = [];
  loading.value = true;
  
  try {
    // 获取聊天历史记录
    const response = await getChatHistory(userStore.userId, contact.id, 1, 50);
    if (response.code === 200) {
      messages.value = response.data.records || [];
      scrollToBottom();
      
      // 标记所有消息为已读
      if (contact.unreadCount > 0) {
        markAllAsRead(userStore.userId);
        contact.unreadCount = 0;
      }
    }
  } catch (error) {
    console.error('获取聊天记录失败', error);
    ElMessage.error('获取聊天记录失败');
  } finally {
    loading.value = false;
  }
};

// 发送文本消息
const sendTextMessage = async () => {
  if (!messageText.value.trim() || !currentContact.value) {
    return;
  }
  
  const messageData = {
    receiverId: currentContact.value.id,
    content: messageText.value.trim(),
    type: 'text',
    senderId: userStore.userId,
    sendTime: new Date()
  };
  
  try {
    // 先添加到本地消息列表中
    messages.value.push(messageData);
    scrollToBottom();
    
    // 清空输入框
    messageText.value = '';
    
    // 发送消息到服务器
    const response = await sendMessage(messageData);
    if (response.code !== 200) {
      ElMessage.error('发送失败');
    }
  } catch (error) {
    console.error('发送消息失败', error);
    ElMessage.error('发送失败');
  }
};

// 上传并发送图片
const uploadImage = async (options) => {
  if (!currentContact.value) {
    ElMessage.warning('请先选择联系人');
    return;
  }
  
  const { file } = options;
  try {
    const response = await uploadChatImage(file);
    if (response.code === 200) {
      // 发送图片消息
      const messageData = {
        receiverId: currentContact.value.id,
        content: response.data, // 图片URL
        type: 'image',
        senderId: userStore.userId,
        sendTime: new Date()
      };
      
      // 先添加到本地消息列表中
      messages.value.push(messageData);
      scrollToBottom();
      
      // 发送消息到服务器
      await sendMessage(messageData);
    } else {
      ElMessage.error('图片上传失败');
    }
  } catch (error) {
    console.error('图片上传失败', error);
    ElMessage.error('图片上传失败');
  }
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messageContainer.value) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
    }
  });
};

// 监听消息变化，自动滚动到底部
watch(messages, () => {
  scrollToBottom();
});

// 初始化
onMounted(() => {
  loadContacts();
  initWebSocket();
});

// 组件销毁时关闭WebSocket连接
onUnmounted(() => {
  if (socket.value) {
    socket.value.close();
  }
});
</script>

<style scoped>
.message-center {
  padding: 20px;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.chat-container {
  height: calc(100vh - 160px);
  min-height: 500px;
  width: 100%;
}

.chat-layout {
  display: flex;
  height: 100%;
  width: 100%;
}

.contacts-list {
  width: 250px;
  border-right: 1px solid #ebeef5;
  display: flex;
  flex-direction: column;
}

.search-box {
  padding: 10px;
  border-bottom: 1px solid #ebeef5;
}

.contacts-scroll {
  flex: 1;
  overflow-y: auto;
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 10px;
  cursor: pointer;
  position: relative;
}

.contact-item:hover {
  background-color: #f5f7fa;
}

.contact-item.active {
  background-color: #ecf5ff;
}

.contact-info {
  margin-left: 10px;
  flex: 1;
}

.contact-name {
  font-weight: 500;
}

.contact-role {
  font-size: 12px;
  color: #909399;
}

.unread-badge {
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 20px;
  height: 20px;
  background-color: #f56c6c;
  color: white;
  border-radius: 10px;
  padding: 0 6px;
  font-size: 12px;
}

.chat-window {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-header {
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  font-weight: 500;
  display: flex;
  align-items: center;
}

.chat-header .contact-role {
  margin-left: 8px;
  font-size: 12px;
  color: #909399;
}

.chat-messages {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}

.empty-messages {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.message-item {
  display: flex;
  margin-bottom: 15px;
  align-items: flex-start;
}

.message-item.message-self {
  flex-direction: row-reverse;
}

.message-content {
  margin: 0 10px;
  max-width: 70%;
}

.message-item.message-self .message-content {
  text-align: right;
}

.message-text {
  background-color: #f2f6fc;
  border-radius: 4px;
  padding: 10px;
  word-break: break-word;
}

.message-item.message-self .message-text {
  background-color: #ecf5ff;
}

.message-image img {
  max-width: 100%;
  max-height: 300px;
  border-radius: 4px;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.chat-input {
  padding: 15px;
  border-top: 1px solid #ebeef5;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}
</style> 